import 'dart:async';
import 'package:flutter/material.dart';
import 'package:znmm/network/notify_listener.dart';
import 'package:intl/intl.dart';
import '../mag/tool_box_mag.dart';

class ToolTopView extends StatefulWidget {
  const ToolTopView({super.key});

  @override
  State<ToolTopView> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<ToolTopView> {
  Timer? _timer; // 定时器引用

  String _time = '';

  double _exchangeRate = 0.0; // 汇率数据
  int _iNotiId1 = -1;

  @override
  void initState() {
    super.initState();
    _updateTime();
    _timer =
        Timer.periodic(const Duration(seconds: 1), (Timer t) => _updateTime());

    ToolBoxMag().fetchData();

    //添加监听者
    _iNotiId1 = NotifyCenter().addObserver(NotifyKey.toolBoxKey, (object) {
      if (mounted) {
        setState(() {
          _exchangeRate = object;
        });
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();

    NotifyCenter().removeCallback(_iNotiId1);

    super.dispose();
  }

  void _updateTime() {
    final now =
        DateTime.now().toUtc().add(const Duration(hours: 0)); // 伦敦时区 UTC+0
    if (mounted) {
      setState(() {
        _time = DateFormat('HH:mm:ss').format(now);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      //mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // 时间显示部分
        Container(
          width: 180,
          //color: Colors.amber,
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '中时区:英国伦敦',
                style: TextStyle(color: Colors.grey, fontSize: 14),
              ),
              const SizedBox(height: 4),
              Text(
                _time,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                '${DateFormat('MM-dd').format(DateTime.now())} 周${_getWeekday()}',
                style: const TextStyle(color: Colors.grey, fontSize: 14),
              ),
            ],
          ),
        ),

        // 垂直分割线
        Container(
          width: 1,
          height: 50,
          color: Colors.grey[300],
        ),
        // 顶部时钟和汇率
        Expanded(child: _buildTopCard())
      ],
    );
  }

  // 汇率区域
  Widget _buildTopCard() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
                color: Colors.grey.withOpacity(0.2),
                blurRadius: 8,
                spreadRadius: 2),
          ],
        ),
        child: Column(
          children: [
            Row(
              children: [
                const Expanded(
                    child: Text(
                  '当前汇率: \n(USD -> CNY)',
                  style: TextStyle(fontSize: 16, color: Colors.grey),
                )),
                IconButton(
                  icon: const Icon(Icons.refresh),
                  tooltip: '刷新',
                  onPressed: () {
                    ToolBoxMag().fetchData();
                  },
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              _exchangeRate == 0.0
                  ? '加载中...'
                  : '100 = ${(100 * _exchangeRate).toStringAsFixed(2)}',
              style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.orange),
            ),
          ],
        ),
      ),
    );
  }

  String _getWeekday() {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    return weekdays[DateTime.now().weekday % 7];
  }
}
